package cn.tedu.csmall.passport.repo.impl;

import cn.tedu.csmall.passport.pojo.vo.AdminListItemVO;
import cn.tedu.csmall.passport.pojo.vo.AdminStandardVO;
import cn.tedu.csmall.passport.repo.IAdminRedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Repository
public class AdminRedisRepositoryImpl implements IAdminRedisRepository {
    @Autowired
    RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public void save(AdminStandardVO adminStandardVO) {
        String key=ADMIN_ITEM_KEY_PREFIX+adminStandardVO.getId();
        redisTemplate.opsForSet().add(ADMIN_ITEM_KEYS_KEY,key);
        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        ops.set(key,adminStandardVO);
    }

    @Override
    public void save(List<AdminListItemVO> admins) {
        String key =ADMIN_LIST_KEY ;
        for (AdminListItemVO admin : admins) {
            redisTemplate.opsForList().rightPush(key,admin);
        }
    }

    @Override
    public List<AdminListItemVO> list() {
        long start=0;
        long end=-1;
        return list(start,end);
    }

    @Override
    public List<AdminListItemVO> list(Long start, Long end) {
        String key=ADMIN_LIST_KEY;
        List<Serializable> range = redisTemplate.opsForList().range(key, start, end);
        List<AdminListItemVO> list = new ArrayList<>();
        for (Serializable item : range) {
           list.add((AdminListItemVO)item);
        }
return list;
    }

    @Override
    public AdminStandardVO get(Long id) {
        String key =ADMIN_ITEM_KEY_PREFIX+id;
        Serializable serializable = redisTemplate.opsForValue().get(key);
        AdminStandardVO admin = (AdminStandardVO) serializable;
        return admin;
    }

    @Override
    public Long deleteAll() {
        SetOperations<String, Serializable> ops = redisTemplate.opsForSet();
        Set<Serializable> members = ops.members(ADMIN_ITEM_KEYS_KEY);
        Set<String> keys= new HashSet<>();
        for (Serializable member : members) {
            keys.add((String) member);
        }
        Long delete = redisTemplate.delete(keys);
        return delete;
    }
}
